package client

import (
	"chess_platform/internal/algo"
	. "chess_platform/internal/common"
	"errors"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

// 创建亲友圈
func NewClub(club map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	values, sql := InsertSql(TableClub, club)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

// 更新亲友圈
func UpdateClub(club map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableClub, club, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//统计亲友圈管理员数量(因为每个亲友圈管理员数有限制)
func CountClubAdmin(clubId int64) int64 {
	//先获取亲友圈成员的id
	sql := fmt.Sprintf(`
		SELECT
			COUNT(uid)
		FROM
			%v
		WHERE
			cid = %v AND role = %v
		`, TableClubMember, clubId, ClubRoleAdmin)
	o := NewDBOrm(DBChess)
	var num int64
	o.Raw(sql).QueryRow(&num)
	return num
}

//更新亲友圈成员总数
func UpdateClubMemberNum(clubId int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	var member int64
	//亲友圈成员数
	sqlClubMember := fmt.Sprintf(`
			SELECT
				COUNT(1)
			FROM
				%v
			WHERE
				cid = ? AND status IN (%v,%v)
		`, TableClubMember, ClubMemberMute, ClubMemberNormal)
	o.Raw(sqlClubMember, clubId).QueryRow(&member)
	sql := fmt.Sprintf("UPDATE %v SET `member` =  %v WHERE id = %v",
		TableClub, member, clubId)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//查找亲友圈
func ClubMapById(uid, cid int64, multiOrm ...orm.Ormer) (orm.Params, error) {
	sql := fmt.Sprintf(`
		SELECT
			c.status AS club_status,c.*,
			u.nickname AS host_name,u.rmcard,u.rmcard_forze,u.imageurl,
			cm.role,cm.status AS member_status
		FROM
			%v AS cm
		LEFT JOIN
			%v AS c
		ON cm.cid = c.id
		LEFT JOIN
			%v AS u
		ON u.uid = c.host_id
		WHERE
			cm.uid = ? AND cm.cid = ?
		`, TableClubMember, TableClub, TableClientUser)
	o := NewOrm(multiOrm, DBChess)
	var club []orm.Params
	_, err := o.Raw(sql, uid, cid).Values(&club)
	if CheckNoExist(err) || len(club) < 1 {
		return nil, nil
	}
	return club[0], err
}

//查询亲友圈，返回是结构体
func ClubStructById(id int64, multiOrm ...orm.Ormer) (Club, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = ?
		LIMIT 1
		`, TableClub)
	o := NewOrm(multiOrm, DBChess)
	var club Club
	err := o.Raw(sql, id).QueryRow(&club)
	if CheckNoExist(err) {
		return club, nil
	}
	return club, err
}

//查询亲友圈，返回是结构体,已经解散的亲友圈不返回
func ClubStructByPassword(password int64, multiOrm ...orm.Ormer) (Club, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			password = ? AND status IN (%v,%v)
		LIMIT 1
		`, TableClub, ClubNormal, ClubFrozen)
	o := NewOrm(multiOrm, DBChess)
	var club Club
	err := o.Raw(sql, password).QueryRow(&club)
	if CheckNoExist(err) {
		return club, nil
	}
	return club, err
}

//玩家参与过的亲友圈列表,解散之后的亲友圈不展示
func ListClub(p ListParams, uid int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			c.status AS club_status,c.*,
			u.nickname AS host_name,u.rmcard,u.rmcard_forze,u.imageurl,
			cm.role,cm.status AS member_status
		FROM
			%v AS cm
		LEFT JOIN
			%v AS c
		ON cm.cid = c.id
		LEFT JOIN
			%v AS u
		ON u.uid = c.host_id
		WHERE
			cm.uid = %v AND cm.status IN (%v,%v) AND c.status != %v
		LIMIT ?,?
		`, TableClubMember, TableClub, TableClientUser, uid, ClubMemberNormal, ClubMemberMute, ClubDismiss)
	o := NewOrm(multiOrm, DBChess)
	var club []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&club)
	if CheckError(err) {
		return club, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			COUNT(DISTINCT cid)
		FROM
			%v AS cm
		LEFT JOIN
			%v AS c
		ON cm.cid = c.id
		WHERE
			cm.uid = %v AND cm.status IN (%v,%v) AND c.status != %v`,
		TableClubMember, TableClub, uid, ClubMemberMute, ClubMemberNormal, ClubDismiss)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return club, count, err
}

//统计每个亲友圈成员在线人数
func StatClubMemberOnline(club ...orm.Params) {
	//只有状态为正常或禁言的才算亲友圈成员
	sql := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v AS cm
		INNER JOIN
			%v AS o
		ON cm.uid = o.uid
		WHERE
			cm.status IN (%v,%v) AND cm.cid = ?
	`, TableClubMember, TableOnlineDetail, ClubMemberNormal, ClubMemberMute)
	o := NewDBOrm(DBChess)
	var onlineNum int64
	for _, v := range club {
		onlineNum = 0
		o.Raw(sql, v["id"]).QueryRow(&onlineNum) //id
		v["online_num"] = onlineNum
		v["list_floor"], _, _ = ListFloor(ListParams{PageSize: 100, PageIndex: 1}, v["id"])
	}
}

//统计用户已经创建正常及冻结的亲友圈个数
func StatPlayerClubNum(uid int64) int64 {
	sql := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			status IN (%v,%v) AND host_id = %v
	`, TableClub, ClubNormal, ClubFrozen, uid)
	o := NewDBOrm(DBChess)
	var clubNum int64
	o.Raw(sql).QueryRow(&clubNum)
	return clubNum
}

//列出要导入的俱乐部成员
func ListImportMember(fromId []int64, multiOrm ...orm.Ormer) (uid []int64, err error) {
	//获取
	cid := Join(fromId, ",")
	sql := fmt.Sprintf(`
		SELECT
			DISTINCT uid
		FROM
			%v
		WHERE
			cid IN (%v) AND status IN (%v,%v)
	`, TableClubMember, cid, ClubMemberNormal, ClubMemberMute)
	o := NewOrm(multiOrm, DBChess)
	_, err = o.Raw(sql).QueryRows(&uid)
	if CheckNoExist(err) {
		return uid, nil
	}
	return
}

// 加入亲友圈,如果已经存在就直接更新
func NewClubMember(cm map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	values, sql := InsertOrUpdateSql(TableClubMember, cm)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//更新亲友圈成员，如状态，角色
func UpdateClubMemberById(data map[string]interface{}, uid, clubId int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	cond := fmt.Sprintf(" uid=%v AND cid = %v ", uid, clubId)
	values, sql := UpdateSql(TableClubMember, data, cond)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//判断亲友圈是否已经存在此成员了
func IsClubMemberExist(clubId, uid int64, multiOrm ...orm.Ormer) (status, role int64, ok bool) {
	sql := fmt.Sprintf(`
		SELECT
			status,role
		FROM
			%v
		WHERE
			uid = ? AND cid = ?
		LIMIT 1
		`, TableClubMember)
	o := NewOrm(multiOrm, DBChess)
	err := o.Raw(sql, uid, clubId).QueryRow(&status, &role)
	//这里应该是不存在就返回false,其它报错之类的就表示已存在,这样就不会误判
	if CheckNoExist(err) {
		return 0, 0, false
	}
	return status, role, true
}

type Member struct {
	Uid    int64 `json:"uid"`
	Status int64 `json:"status"`
	Role   int64 `json:"role"`
}

func listHostAndAdminByFloorId(floorId int64, multiOrm ...orm.Ormer) ([]Member, error) {
	sql := fmt.Sprintf(`
		SELECT
			cm.uid,cm.role,cm.status
		FROM
			%v AS cr
		LEFT JOIN
			%v AS cm
		ON cr.club_id = cm.cid
		WHERE
			cr.id = ? AND cm.role IN (%v,%v)
		`, TableClubFloor, TableClubMember, ClubRoleAdmin, ClubRoleOwner)

	var m []Member
	o := NewOrm(multiOrm, DBChess)
	_, err := o.Raw(sql, floorId).QueryRows(&m)
	if CheckNoExist(err) {
		return m, nil
	}
	return m, err
}

func IsHostAndAdminByFloorId(floorId, uid int64, multiOrm ...orm.Ormer) bool {
	m, err := listHostAndAdminByFloorId(floorId, multiOrm...)
	if err != nil {
		LogClient.Error(fmt.Sprintf("根据楼层id列出创建人及管理员出错:%v", err))
		return false
	}
	for _, v := range m {
		if v.Uid == uid && v.Status == ClubMemberNormal {
			return true
		}
	}
	return false
}

func IsHostByFloorId(floorId, uid int64, multiOrm ...orm.Ormer) bool {
	m, err := listHostAndAdminByFloorId(floorId, multiOrm...)
	if err != nil {
		LogClient.Error(fmt.Sprintf("根据楼层id列出创建人及管理员出错:%v", err))
		return false
	}
	for _, v := range m {
		if v.Uid == uid && v.Role == ClubRoleOwner && v.Status == ClubMemberNormal {
			return true
		}
	}
	return false
}

//亲友圈成员列表(正常及禁言的成员)(要做排序,创建人在最前面,然后是管理员,最后是在线的远近)
func ListClubMember(p ListParams, clubId, uid int64, name string, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf("cm.cid = %v AND cm.status IN (%v,%v)", clubId, ClubMemberNormal, ClubMemberMute)
	if uid != 0 {
		where = where + fmt.Sprintf(" AND cm.uid = %v", uid)
	} else if name != "" {
		where = where + fmt.Sprintf(" AND u.nickname LIKE '%v'", "%"+name+"%")
	}

	sql := fmt.Sprintf(`
		SELECT
			u.nickname,u.imageurl AS head_img,cm.*
		FROM
			%v AS cm
		LEFT JOIN
			%v AS u
		ON cm.uid = u.uid
		WHERE
		 	%v
		ORDER BY cm.role DESC,u.offlinetime DESC
		LIMIT ?,?
		`, TableClubMember, TableClientUser, where)
	o := NewOrm(multiOrm, DBChess)
	var cm []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cm)
	if CheckError(err) {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v AS cm
		LEFT JOIN
			%v AS u
		ON cm.uid = u.uid
		WHERE %v`,
		TableClubMember, TableClientUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return cm, count, err
}

//俱乐部在线成员(要在俱乐部中的才行)
func ListClubOnlineMember(p ListParams, clubId int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf("clubid = %v", clubId)

	sql := fmt.Sprintf(`
		SELECT
			roomid,uid
		FROM
			%v
		WHERE
		 	%v
		LIMIT ?,?
		`, TableOnlineDetail, where)
	o := NewOrm(multiOrm, DBChess)
	var cm []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cm)
	if CheckError(err) {
		return cm, 0, err
	}
	for _, v := range cm {
		u, _ := QueryUserInfoById(v["uid"])
		v["nickname"] = u.Nickname
		v["head_img"] = u.ImageUrl
	}

	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE %v`,
		TableOnlineDetail, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return cm, count, err
}

//获取亲友圈成员列表的在线状态及离线多久，这些数据是变动的,
// 把变动频繁的数据与变动频率低的数据分开，方便变动频率低的数据缓存
func ClubMemberOnlineStatus(clubMember []orm.Params) {
	sqlOnline := fmt.Sprintf(`
		SELECT
			uid AS online_status
		FROM
			%v
		WHERE
			uid = ?
	`, TableOnlineDetail)
	sqlOffline := fmt.Sprintf(`
		SELECT
			offlinetime
		FROM
			%v
		WHERE
			uid = ?
	`, TableClientUser)
	o := NewDBOrm(DBChess)
	var onlineStatus, offlineTime int64
	for _, v := range clubMember {
		onlineStatus = 0
		offlineTime = 0
		o.Raw(sqlOnline, v["uid"]).QueryRow(&onlineStatus)
		v["online_status"] = onlineStatus
		o.Raw(sqlOffline, v["uid"]).QueryRow(&offlineTime)
		if onlineStatus == 0 {
			v["offline_time"] = OfflineTime(offlineTime)
		}
	}
}

//亲友圈成员列表(待审核的成员)
func ListAuditClubMember(p ListParams, clubId int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf("cm.cid = %v AND cm.status = %v", clubId, ClubMemberAudit)
	sql := fmt.Sprintf(`
		SELECT
			u.nickname,u.imageurl AS head_img,c.name AS club_name,c.password
			cm.cid AS club_id,cm.uid,cm.role,cm.create_time
		FROM
			%v AS cm
		LEFT JOIN
			%v AS u
		ON cm.uid = u.uid
		LEFT JOIN
			%v AS c
		ON c.id = cm.cid
		WHERE
			 %v
		LIMIT ?,?
		`, TableClubMember, TableClientUser, TableClub, where)
	o := NewOrm(multiOrm, DBChess)
	var cm []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cm)
	if CheckError(err) {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE  %v`,
		TableClubMember, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return cm, count, nil
}

//管理员或创建人参与的所有亲友圈待审核的成员列表(待审核的成员)
func ListAllAuditClubMember(p ListParams, uid int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	//亲友圈解散了的要排除,管理员及亲友圈创建人才能审核
	sql := fmt.Sprintf(`
		SELECT
			u.nickname,u.imageurl AS head_img,
			cm.create_time,cm.uid,c.id AS club_id,c.name AS club_name,c.password
		FROM
			%v AS cm
		LEFT JOIN
			%v AS u
		ON cm.uid = u.uid
		LEFT JOIN
			%v AS c
		ON c.id = cm.cid
		WHERE
			cm.cid IN (SELECT cid FROM %v WHERE uid = %v AND role IN (%v,%v)) AND cm.status = %v AND c.status != %v
		LIMIT ?,?
		`, TableClubMember, TableClientUser, TableClub, TableClubMember, uid, ClubRoleAdmin, ClubRoleOwner, ClubMemberAudit, ClubDismiss)
	o := NewOrm(multiOrm, DBChess)
	var cm []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cm)
	if CheckError(err) {
		return nil, 0, err
	}
	//没有把条件写齐，没把连表的条件写进来，返回的总数比较真实的多,但不太影响
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE cid = %v AND status = %v AND role IN (%v,%v)`,
		TableClubMember, uid, ClubMemberAudit, ClubRoleOwner, ClubRoleAdmin)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return cm, count, nil
}

//亲友圈冻结,解散,恢复正常时要发送邮件给全部亲友圈成员
func SendEmailToClubMember(content, title, action string, clubId int64, multiOrm ...orm.Ormer) error {
	data := map[string]interface{}{
		"type":      EmailTypeSys,
		"suid":      0,
		"nickname":  "系统消息",
		"title":     title,
		"content":   content,
		"status":    0,
		"send_time": time.Now().Unix(),
	}
	userId := ListAllClubMember(clubId)
	for _, uid := range userId {
		data["ruid"] = uid
		_, err := NewEmail(data, multiOrm...)
		if err != nil {
			return err
		}
	}
	onlineUid := ListAllOnlineClubMember(clubId)
	ok := BroadCastMsgToLobby(clubId, GenBroadcastMsg(ModuleEmail, ActionNewEmail, ""), onlineUid...)
	if !ok {
		return errors.New("发送邮件通知,游戏服务器大厅返回失败")
	}
	ok = BroadCastMsgToLobby(clubId, GenBroadcastMsg(ModuleClub, action, clubId), onlineUid...)
	if !ok {
		return errors.New("发送亲友圈变动通知,游戏服务器大厅返回失败")
	}

	return nil
}

//亲友圈成员加入时要通知亲友圈管理员及创建人
func ListClubHostAndAdmin(clubId int64) []int64 {
	//先获取亲友圈成员的id
	sql := fmt.Sprintf(`
		SELECT
			uid
		FROM
			%v
		WHERE
			cid = %v AND status = %v AND role IN(%v,%v)
		`, TableClubMember, clubId, ClubMemberNormal, ClubRoleAdmin, ClubRoleOwner)
	o := NewDBOrm(DBChess)
	var uid []int64
	_, err := o.Raw(sql).QueryRows(&uid)
	if CheckNoExist(err) {
		return uid
	}
	return uid
}

//发送消息给亲友圈创建人及管理员
func NotifyClubHostAndAdmin(clubId int64, msg string) error {
	userId := ListClubHostAndAdmin(clubId)
	ok := BroadCastMsgToLobby(0, msg, userId...)
	if !ok {
		return errors.New("发送邮件通知,游戏服务器大厅返回失败")
	}
	return nil
}

//亲友圈所有在线成员
func ListAllOnlineClubMember(clubId int64) []int64 {
	//先获取亲友圈成员的id
	sql := fmt.Sprintf(`
		SELECT
			o.uid
		FROM
			%v AS cm
		INNER JOIN
			%v AS o
		ON o.uid = cm.uid
		WHERE
			cm.cid = %v AND cm.status IN (%v,%v)
		`, TableClubMember, TableOnlineDetail, clubId, ClubMemberNormal, ClubMemberMute)
	o := NewDBOrm(DBChess)
	var uid []int64
	o.Raw(sql).QueryRows(&uid)
	return uid
}

//亲友圈所有成员
func ListAllClubMember(clubId int64) []int64 {
	//先获取亲友圈成员的id
	sql := fmt.Sprintf(`
		SELECT
			uid
		FROM
			%v
		WHERE
			cid = %v AND status IN (%v,%v)
		`, TableClubMember, clubId, ClubMemberNormal, ClubMemberMute)
	o := NewDBOrm(DBChess)
	var uid []int64
	o.Raw(sql).QueryRows(&uid)
	return uid
}

//回收一个亲友圈号
func RecycleClubNumber(password interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	sqlUpdate := fmt.Sprintf(`UPDATE %v SET club_use = 0 WHERE id = %v`, TableIdFactory, password)
	result, err := o.Raw(sqlUpdate).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//从数据库里获取一个亲友圈号
func GetNormalClubNumber(multiOrm ...orm.Ormer) int64 {
	n := algo.Random(100000, 999999)
	var number int64
	sqlGet := fmt.Sprintf(`
		SELECT
			MAX(id) AS id
		FROM
			%v
		WHERE
			is_good = 0 AND club_use = 0 AND id < %v AND id >= 100000
		LIMIT 1
	`, TableIdFactory, n)
	o := NewOrm(multiOrm, DBChess)
	o.Raw(sqlGet).QueryRow(&number)
	if number == 0 { //没有找到
		sqlGet = fmt.Sprintf(`
			SELECT
				MAX(id) AS id
			FROM
				%v
			WHERE
				is_good = 0 AND club_use = 0 AND id > %v AND id <= 999999
			LIMIT 1
	`, TableIdFactory, n)
		o.Raw(sqlGet).QueryRow(&number)
		if number == 0 {
			LogClient.Error("亲友圈ID已经使用完毕,请注意")
			return 0
		}
	}
	sqlUpdate := fmt.Sprintf(`UPDATE %v SET club_use = 1 WHERE id = %v`, TableIdFactory, number)
	o.Raw(sqlUpdate).Exec()
	return number
}

//从数据库里获取一个玩家uid
func GetNormalPlayerUid(multiOrm ...orm.Ormer) int64 {
	n := algo.Random(100000, 999999)
	var number int64
	sqlGet := fmt.Sprintf(`
		SELECT
			MAX(id) AS id
		FROM
			%v
		WHERE
			is_good = 0 AND user_use = 0 AND id < %v AND id >= 100000
		LIMIT 1
	`, TableIdFactory, n)
	o := NewOrm(multiOrm, DBChess)
	o.Raw(sqlGet).QueryRow(&number)
	if number == 0 { //没有找到
		sqlGet = fmt.Sprintf(`
			SELECT
				MAX(id) AS id
			FROM
				%v
			WHERE
				is_good = 0 AND user_use = 0 AND id > %v AND id <= 999999
			LIMIT 1
	`, TableIdFactory, n)
		o.Raw(sqlGet).QueryRow(&number)
		if number == 0 {
			LogClient.Error("玩家ID已经使用完毕,请注意")
			return 0
		}
	}
	sqlUpdate := fmt.Sprintf(`UPDATE %v SET user_use = 1 WHERE id = %v`, TableIdFactory, number)
	o.Raw(sqlUpdate).Exec()
	return number
}

//从数据库里获取一个代理uid
func GetNormalAgentUid(multiOrm ...orm.Ormer) int64 {
	n := algo.Random(100000, 999999)
	var number int64
	sqlGet := fmt.Sprintf(`
		SELECT
			MAX(id) AS id
		FROM
			%v
		WHERE
			is_good = 0 AND agent_use = 0 AND id < %v AND id >= 100000
		LIMIT 1
	`, TableIdFactory, n)
	o := NewOrm(multiOrm, DBChess)
	o.Begin()
	defer o.Rollback()
	o.Raw(sqlGet).QueryRow(&number)
	if number == 0 { //没有找到
		sqlGet = fmt.Sprintf(`
			SELECT
				MAX(id) AS id
			FROM
				%v
			WHERE
				is_good = 0 AND agent_use = 0 AND id > %v AND id <= 999999
			LIMIT 1
	`, TableIdFactory, n)
		o.Raw(sqlGet).QueryRow(&number)
		if number == 0 {
			o.Rollback()
			LogClient.Error("代理ID已经使用完毕,请注意")
			return 0
		}
	}
	sqlUpdate := fmt.Sprintf(`UPDATE %v SET agent_use = 1 WHERE id = %v`, TableIdFactory, number)
	_, err := o.Raw(sqlUpdate).Exec()
	if err != nil {
		o.Rollback()
		return 0
	}
	o.Commit()
	return number
}

//------------------------------俱乐部楼层改版之后的-----------------------------------
// 创建楼层
func NewClubFloor(club map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	values, sql := InsertSql(TableClubFloor, club)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

// 更新楼层
func UpdateClubFloor(club map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableClubFloor, club, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//TODO:要做缓存
//列出楼层
func ListFloor(p ListParams, clubId interface{}, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf("club_id = %v AND  is_delete = 0", clubId)
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
		 	%v
		LIMIT ?,?
		`, TableClubFloor, where)
	o := NewOrm(multiOrm, DBChess)
	var cm []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cm)
	if CheckError(err) {
		return cm, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE %v`,
		TableClubFloor, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return cm, count, err
}

func CountFloor(clubId int64, multiOrm ...orm.Ormer) (int64, error) {
	where := fmt.Sprintf("club_id = %v AND  is_delete = 0", clubId)
	sql := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE %v`,
		TableClubFloor, where)
	var count int64
	o := NewOrm(multiOrm, DBChess)
	err := o.Raw(sql).QueryRow(&count)
	return count, err
}
